﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;
using Microsoft.VisualStudio.TextTemplating;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
namespace T4Common
{
    public class VSContext
    {

        /// <summary>
        /// 可能tt模版需要启用 hostSpecific="true"  <#@ hostSpecific="true" language="C#" #>
        /// </summary>
        /// <param name="engineHost"></param>
        public VSContext(ITextTemplatingEngineHost engineHost)
        {
            ServiceProvider serviceProvider = new ServiceProvider(engineHost as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
            var dte = (DTE)serviceProvider.GetService(typeof(DTE));
            this.currentSolution = dte.Solution;
        }

        /// <summary>
        /// 可能tt模版需要启用 hostSpecific="true"  <#@ hostSpecific="true" language="C#" #>
        /// </summary>
        /// <param name="dte"></param>
        public VSContext(DTE dte)
        {
            this.currentSolution = dte.Solution;
        }

        public VSContext()
        {
            throw new NotImplementedException();
        }

        Solution currentSolution;
        /// <summary>
        /// 当前解决方案
        /// </summary>
        public Solution CurrentSolution
        {
            get
            {
                return currentSolution;
            }
            private set
            {
                this.currentSolution = value;
            }
        }


        public Project Project(string projectName)
        {
            return this.Project(this.currentSolution, projectName);
        }

        public Project Project(Solution solution, string projectName)
        {
            Project value = null;
            if(solution.Projects == null || solution.Projects.Count == 0)
                return null;
            foreach (Project project in solution.Projects)
            {
                if (project.Name.Equals(projectName, StringComparison.CurrentCulture))
                {
                    value = project;
                    break;
                }
            }
            return value;
        }
    }
}
